package com.hanko.oauth.config.provider;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

@Component
@Slf4j
public class AuthService {
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    public boolean canAccess(HttpServletRequest request, Authentication authentication) {
        AtomicBoolean canBe = new AtomicBoolean(true);
        Object principal = authentication.getPrincipal();
        if (principal == null) {
            canBe.set(false);
        }

        Set<String> roles = authentication.getAuthorities()
                .stream()
                .map(e -> e.getAuthority())
                .collect(Collectors.toSet());

        String uri = request.getRequestURI();

        //根据client_id = principal 或用户名关联角色取出资源Urls
        Set<String> urls = new HashSet<>();
        urls.add("/index/**");
        urls.forEach(url -> {
            if (antPathMatcher.match(url, uri)) {
                canBe.set(true);
            }
        });

        //check this uri can be access by this role
        return canBe.get();

    }
}
